﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using eStore.Models;

namespace eStore.Controllers
{
    public class CheckOutController : Controller
    {
        //
        // GET: /CheckOut/

        [Authorize]
        public ActionResult Index()
        {
            var shoppingCart = ShoppingCart.GetCart(this.HttpContext, false);
            List<CartItem> oCartItems = null;

            if (shoppingCart != null)
                oCartItems= shoppingCart.GetAllCartItems();
            if (oCartItems == null || !(oCartItems.Any()) || oCartItems.Count<1)
                return RedirectToAction("Index", "Home", null);

            CheckOutModel oCheckOutModel = new CheckOutModel();
            oCheckOutModel.UserName = HttpContext.User.Identity.Name;

            return View(oCheckOutModel);
        }

        [HttpPost]
        [Authorize]
        public ActionResult Index([Bind]CheckOutModel checkOutModel )
        {
            var shoppingCart = ShoppingCart.GetCart(this.HttpContext, false);
            Order oNewOrder = null;
            if (ModelState.IsValid) {
                oNewOrder = shoppingCart.CreateOrder(checkOutModel);
                if (oNewOrder != null)
                {
                    shoppingCart = ShoppingCart.GetCart(this.HttpContext, true);
                    return View("Success",oNewOrder);
                }
                else
                {
                    ModelState.AddModelError("_Form", "Order is not created");
                }
            }

            return View(checkOutModel);
        }

    }
}
